//
//  BalanceBuleManager.m
//  BalanceCar
//
//  Created by 郑信鸿 on 2017/8/30.
//  Copyright © 2017年 郑信鸿. All rights reserved.
//

#import "BalanceBuleManager.h"
#import "WLButtonCountdownManager.h"

static NSString *const TX_SERVICE_UUID = @"FFE5";
static NSString *const RX_SERVICE_UUID = @"FFE0";

static NSString *const RX_CHAR_UUID = @"FFE4";
static NSString *const TX_CHAR_UUID = @"FFE9";


@interface BalanceBuleManager ()<CBCentralManagerDelegate,CBPeripheralDelegate>

@property (strong, nonatomic)CBCentralManager *centralManager;/**< 中心管理器 */

@property (strong, nonatomic) CBCharacteristic *txCharacteristic;

@property (strong, nonatomic) CBCharacteristic *rxCharacteristic;

@end

@implementation BalanceBuleManager

+ (BalanceBuleManager *)shareManager
{
    static BalanceBuleManager *managerInstance = nil;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        managerInstance = [[self alloc] init];
    });
    return managerInstance;
}


- (instancetype)init{
    
    if (self = [super init]) {
        
        NSDictionary *options = @{CBCentralManagerOptionShowPowerAlertKey:@(YES)};
        _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue() options:options];
        
    }
    return self;
}


//搜索设备
- (void)scanPeripherals{
    
    [_centralManager scanForPeripheralsWithServices:nil options:nil];
 
}

//停止搜索
- (void)stopScan{
    
    [_centralManager stopScan];
}

//链接设备
- (void)conentPeripherals:(CBPeripheral *)peripherals{
    
    [_centralManager connectPeripheral:peripherals options:nil];
    [[WLButtonCountdownManager defaultManager] startCounDown:10 finished:^(NSTimeInterval count) {
       
        if (!count) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kPeripheralConentResultNotification object:@{@"connect":@1}];
        }
        
    }];
    
}

- (void)cancePeripherals{
    
    if (self.connectPeripheral) {
        
        [_centralManager cancelPeripheralConnection:self.connectPeripheral];
        
    }
    
}

//自动连接
- (BOOL)autoConnectPeripherals{
   
    if (![self cacheSrviceUUID]){
        
        return NO;
    }
    //已经被系统或者其他APP连接上的设备数组
    NSArray *arr = [self.centralManager retrieveConnectedPeripheralsWithServices:@[[CBUUID UUIDWithString:[self cacheSrviceUUID]]]];//serviceUUID就是你首次连接配对的蓝牙
    NSLog(@"%@",arr);
    if(arr.count>0)
    {
        for (CBPeripheral* peripheral in arr)
        {
            if (peripheral != nil)
            {
                self.connectPeripheral = peripheral;//这一个必须要，需要一个全局变量接受，否则无法连接
                self.connectPeripheral.delegate = self;
                [self.centralManager connectPeripheral:self.connectPeripheral options:nil];
            }
        }
    }
    
    return  YES;
}

//蓝牙设备的当前状态更新
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kCentralManagerStateUpdateNotification object:@{@"central":central}];
    
}

//发现蓝牙设备
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:KCentralManageDiscoverPeripheralNotification object:@{@"peripheral":peripheral,@"RSSI":RSSI}];
    
}


//设备链接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    
    self.connectPeripheral = peripheral;
    self.connectPeripheral.delegate = self;
    [self.connectPeripheral discoverServices:@[]];
    
   
}


//链接失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    
    if ([WLButtonCountdownManager defaultManager].stop) {
        
        return;
        
    }else{
        
        [[WLButtonCountdownManager defaultManager] stopTask];
        
    }
    
    self.connectPeripheral = nil;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kPeripheralConentResultNotification object:@{@"connect":@1}];
    
}

//断开链接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    self.connectPeripheral = nil;
     [[NSNotificationCenter defaultCenter] postNotificationName:kPeripheralDisConnectNotification object:@{@"disConnect":@0}];
    [[UIApplication sharedApplication].keyWindow.rootViewController dismissViewControllerAnimated:YES completion:NULL];
}


#pragma mark - 设备

- (void)peripheralWriteData:(NSData *)data{
    
    NSLog(@"发送数据%@",data);
    [self.connectPeripheral writeValue:data forCharacteristic:self.txCharacteristic type:CBCharacteristicWriteWithResponse];
}

//调用discoverServices回调
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    
    
    NSArray *services = peripheral.services;
    
    for (CBService *service in services) {
        NSLog(@"%@",service.UUID.UUIDString);
        if ([service.UUID.UUIDString isEqualToString:RX_SERVICE_UUID]) {
            
            [self.connectPeripheral discoverCharacteristics:@[] forService:service];
        }
        if ([service.UUID.UUIDString isEqualToString:TX_SERVICE_UUID]) {
            [self.connectPeripheral discoverCharacteristics:@[] forService:service];
        }
        
    }
    
}
//调用查找特征discoverCharacteristics后 会回调此方法
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    
    NSArray *characteristics = service.characteristics;
    
    for (CBCharacteristic *characteristic in characteristics) {
        
        
        if ([characteristic.UUID.UUIDString isEqualToString:RX_CHAR_UUID]) {
            
            self.rxCharacteristic = characteristic;
            [self.connectPeripheral setNotifyValue:YES forCharacteristic:self.rxCharacteristic];
        }
        if ([characteristic.UUID.UUIDString isEqualToString:TX_CHAR_UUID]) {
            self.txCharacteristic = characteristic;
        }
    }
    

    
}


//调用readValueForCharacteristic
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    //收的一切数据,基本都从这里得到
    NSLog(@"---收到数据%@",characteristic.value);
    
     NSData *data = characteristic.value;
     [BaseAcceptData analysisData:data];
    
}


- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error{
    NSLog(@"---发送数据%@",characteristic.value);
    
    
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error{
    NSLog(@"--updateNotifucation%@",characteristic.value);
    
//    if (![[NSUserDefaults standardUserDefaults] objectForKey:self.connectPeripheral.identifier.UUIDString]) {
//        
//        [[NSUserDefaults standardUserDefaults] setObject:@"0000" forKey:self.connectPeripheral.identifier.UUIDString];
//        
//    }
    [[NSNotificationCenter defaultCenter] postNotificationName:kPeripheralConentResultNotification object:@{@"connect":@0}];
    [[BalanceBuleManager shareManager] savePeripheraServiceUUID:self.connectPeripheral.identifier.UUIDString];
    
}


- (void)savePeripheraServiceUUID:(NSString *)serviceUUID{
    
    [[NSUserDefaults standardUserDefaults] setObject:serviceUUID forKey:kPeripheraServiceUUID];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString *)cacheSrviceUUID{
    
    return [[NSUserDefaults standardUserDefaults] objectForKey:kPeripheraServiceUUID];
}


@end
